<?php

namespace app\admin\controller;

use app\common\Helper;
use app\lib\exception\ParameterException;

use app\admin\model\Store;

use think\Db;
use think\Exception;
use think\Request;

class Storesettlerule extends Base
{

    public function index(){
        $params = $this->request->param();
        $where = [];

        $model = model('Storesettlerule');
        $info = $model->where($where)->find();

        return $this->fetch('', [
            'info' => $info,
        ]);
    }

    public function save(Request $request){
        $param = $request->param();
        try{
            $param['settleMoneyLimit'] = $param['settleMoneyLimit'] * 100;
            $this->chckParam($param);
        }catch (Exception $e){
            return show(config('status.error_code'), $e->msg, $e->msg);
        }

        $model = model('Storesettlerule');

        if (!empty($param['id'])) {
            // 修改
            $id = $param['id'];
            $param['updateDate'] = date('Y-m-d H:i:s');
            $param['updateOper'] = $this->admin->id;
            $result = $model->allowField(true)->save($param, ['id' => $id]);
        } else {
            // 新增
            $param['id'] = Helper::getUUID();
            $param['createDate'] = date('Y-m-d H:i:s');
            $param['createOper'] = $this->admin->id;
            $result = $model->save($param);
        }

        if ($result !== false) {
            return show(config('status.success_code'), '保存成功', '保存成功');
        } else {
            return show(config('status.error_code'), '保存失败', $model->getError());
        }
    }

    private function chckParam($param){
        if (empty($param['settleTime']) || (int)$param['settleTime']<0) {
            throw new ParameterException([
                'msg' => '提现次数不合法'
            ]);

        }
        if (empty($param['settleMoneyLimit']) || !$this->isCurrency($param['settleMoneyLimit'])){
            throw new ParameterException([
                'msg' => '最高提现金额须大于1'
            ]);
        }
    }
    private function isCurrency($value){
        //$value精确到分
        if($value<100){
            return false;
        }
        if (preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)) {
            return true;
        }else{
            return false;
        }
    }

}